package com.tool.cn.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 控制台工具类
 * 
 * @author wangzh 2018年1月2日 下午3:46:51
 */
public class ConsoleUtil {

	private static final Log log = LogFactory.getLog(ConsoleUtil.class);

	public List<String> submitSH(String cmd) {
		Process proc = null;
		List<String> fileList = new ArrayList<String>();
		int exitCode = -1;
		TrackConsoleMsg trackInf = null;
		try {
			log.info("shellCMD=" + cmd);
			proc = new ProcessBuilder("bash", "-c", cmd).start();

			trackInf = new TrackConsoleMsg(proc.getInputStream(), fileList);
			trackInf.start();
			exitCode = proc.waitFor();
			if (exitCode != 0 && exitCode != 2) {
				 InputStream errorStream = proc.getErrorStream();
				 BufferedReader br = new BufferedReader(new InputStreamReader(errorStream));
				 String errContext="",line;
                 while (true){
                     line = br.readLine();
                     if(line == null) break;
                     errContext+=line;
                 }
				log.error("run is error " + exitCode+" "+errContext);
			}

			trackInf.join();
		} catch (IOException e) {
			log.error("IOException", e);
		} catch (InterruptedException e) {
			log.error(e,e);
		} finally {
			proc.destroy();
		}
		return fileList;
	}

	class TrackConsoleMsg extends Thread {
		private BufferedReader read = null;
		private List<String> list = null;

		public TrackConsoleMsg(InputStream in, List<String> list) {
			read = new BufferedReader(new InputStreamReader(in));
			this.list = list;
		}

		@Override
		public void run() {
			String line = null;
			try {
				line = read.readLine();
				while (null != line && !isInterrupted()) {
					if (line.indexOf("ls: cannot access") < 0) {
						list.add(line);
					}
					line = read.readLine();
				}
			} catch (Exception e) {
				log.error(e,e);
			} finally {
				if (null != read) {
					try {
						read.close();
					} catch (IOException e) {
						log.error(e,e);
					}
				}
			}
		}
	}

}
